package com.tlxch.task;

import com.tlxch.mapper.TAlertMapper;
import com.tlxch.mapper.TAssessMapper;
import com.tlxch.mapper.TTeacherMapper;
import com.tlxch.pojo.TAlert;
import com.tlxch.pojo.TAssess;
import com.tlxch.pojo.TTeacher;
import com.tlxch.websocket.WebSocketServer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

@Component
@Slf4j
public class TAssessTask {

    @Autowired
    TAssessMapper tAssessMapper;
    @Autowired
    WebSocketServer webSocketServer;
    @Autowired
    TTeacherMapper tTeacherMapper;
    @Autowired
    TAlertMapper tAlertMapper;

    @Scheduled(cron = "0 * * * * ? ")
    public void automaticChecks() {
        log.info("自动检查任务开始执行");
        try {
            // 获取评估、教师和预警列表
            List<TAssess> tAssessList = tAssessMapper.getAssessList();
            List<TTeacher> tTeacherList = tTeacherMapper.getTeacherList();
            List<TAlert> tAlertList = tAlertMapper.getAlertList();

            // 构建评估ID到最新预警记录的映射
            Map<Integer, TAlert> assessIdToLatestAlert = new HashMap<>();
            for (TAlert alert : tAlertList) {
                Integer assessId = alert.getTaTaid();
                if (assessId != null) {
                    TAlert latestAlert = assessIdToLatestAlert.get(assessId);
                    if (latestAlert == null || alert.getTaCreatetime().isAfter(latestAlert.getTaCreatetime())) {
                        assessIdToLatestAlert.put(assessId, alert);
                    }
                }
            }

            // 定义需要监控的评估类型
            Set<Integer> monitoredTypes = new HashSet<>(Arrays.asList(1, 2, 4));

            // 遍历评估列表，查找需要预警的记录
            for (TAssess tAssess : tAssessList) {
                Integer assessId = tAssess.getTsId();
                // 检查是否已经存在预警记录
                if (assessId != null &&
                        tAssess.getTsLevel() == 4 &&
                        monitoredTypes.contains(tAssess.getTsType())) {

                    TAlert latestAlert = assessIdToLatestAlert.get(assessId);
                    boolean shouldSendAlert = false;

                    if (latestAlert == null) {
                        // 不存在预警记录，需要创建
                        shouldSendAlert = true;
                    } else {
                        // 存在预警记录，检查是否超过30天
                        LocalDateTime threeDaysAgo = LocalDateTime.now().minusDays(30);
                        if (latestAlert.getTaCreatetime().isBefore(threeDaysAgo) && latestAlert.getTaStatus()==1) {
                            // 超过3天，需要更新预警
                            shouldSendAlert = true;

                            // 更新预警次数
                            latestAlert.setTaCount(latestAlert.getTaCount() + 1);
                            latestAlert.setTaCreatetime(LocalDateTime.now());
                            tAlertMapper.updateByPrimaryKeySelective(latestAlert);
                        } else {
                            log.debug("评估ID {} 的预警记录未超过3天，上次创建时间: {}", assessId, latestAlert.getTaCreatetime());
                        }
                    }

                    if (shouldSendAlert) {
                        // 为每位教师发送预警消息
                        String message = "{\"msg\":\"" + tAssess.getTsSid() + "同学的有评估达到预警状态！\"}";
                        for (TTeacher tTeacher : tTeacherList) {
                            webSocketServer.sendToClient(message, tTeacher.gettTid());
                        }

                        if (latestAlert == null) {
                            // 创建新的预警记录
                            TAlert tAlert = new TAlert();
                            tAlert.setTaSid(tAssess.getTsSid());
                            tAlert.setTaContent(tAssess.getTsSid() + "同学的有评估等级达到预警状态！");
                            tAlert.setTaLevel(tAssess.getTsLevel());
                            tAlert.setTaStatus(1);
                            tAlert.setTaTaid(assessId);
                            tAlert.setTaCreatetime(LocalDateTime.now());
                            tAlert.setTaCount(1);
                            tAlertMapper.insert(tAlert);
                            log.info("新增预警记录，关联评估ID: {}", assessId);

                            // 更新映射
                            assessIdToLatestAlert.put(assessId, tAlert);
                        } else {
                            log.info("更新预警记录，关联评估ID: {}, 次数: {}", assessId, latestAlert.getTaCount());
                        }
                    }
                }
            }
        } catch (Exception e) {
            log.error("自动检查任务执行失败", e);
        }
    }
}